package com.dz.vmp.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Controller
public class ZipController {

    // 用于接收压缩数据并返回解压后的数据
    @PostMapping("/decompress")
    public ResponseEntity<?> decompressData(@RequestBody byte[] data) throws IOException {
        try {
            if (data == null || data.length == 0) {
                return ResponseEntity.badRequest().body("数据为空");
            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
                 GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = gzipInputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
            }
            return ResponseEntity.ok(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("解压失败原因: " + e.getMessage());
        }
    }

    // 用于接收数据并返回压缩后的数据
    @PostMapping("/compress")
    public ResponseEntity<?> compressData(@RequestBody byte[] data) throws IOException {
        try {
            if (data == null || data.length == 0) {
                return ResponseEntity.badRequest().body("数据为空");
            }
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
                gzipOutputStream.write(data);
            }
            return ResponseEntity.ok(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("压缩失败原因: " + e.getMessage());
        }
    }
}
